package com.mcxx.modules.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.modules.system.service.BlacklistService;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.miniSalvation.family.dto.FamilyMemberHistoryDTO;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMemberHistoryReadService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMemberWriteService;
import com.mcxx.modules.miniSalvation.order.dto.AddBlacklistRecordDTO;
import com.mcxx.modules.miniSalvation.order.entity.BlacklistEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.BlacklistReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.BlacklistWriteService;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMemberEntity;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMemberWriteService;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.module.dict.entity.TaDictPo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@TaTransactional
public class BlacklistServiceImpl implements BlacklistService {

    private final static Logger logger = LoggerFactory.getLogger(BlacklistServiceImpl.class);

    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private TmpOrderReadService tmpOrderReadService;
    @Autowired
    private BlacklistWriteService blacklistWriteService;
    @Autowired
    private BlacklistReadService blacklistReadService;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;
    @Autowired
    private TmpFamilyMemberWriteService tmpFamilyMemberWriteService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private DictionaryReadService dictionaryReadService;


    @Override
    public void addRecord(AddBlacklistRecordDTO dto) {

        preCheck4AddRecord(dto);


        List<FamilyMemberHistoryDTO> familyMembers = familyMemberHistoryReadService.listByOrderIdAndIdCards(dto.getOrderId(),dto.getIdcards());
        for (FamilyMemberHistoryDTO familyMember : familyMembers) {
            BlacklistEntity blacklistEntity = new BlacklistEntity();
            blacklistEntity.setId(IdUtil.simpleUUID());
            blacklistEntity.setAreaCode(familyMember.getAreaCode());
            blacklistEntity.setCountyCode(familyMember.getCountyCode());
            blacklistEntity.setFamilyId(familyMember.getFamilyId());
            blacklistEntity.setMemberId(familyMember.getMemberId());
            blacklistEntity.setBusinessCode(familyMember.getBusinessType());
            blacklistEntity.setName(familyMember.getName());
            blacklistEntity.setIdcard(familyMember.getIdcard());
            blacklistEntity.setFamilyNum(familyMember.getFamilyMemberNumber());
            blacklistEntity.setBusiStatus(familyMember.getOrderState());
            blacklistEntity.setStatus(1);
            blacklistEntity.setAddDate(dto.getAddDate());
            blacklistEntity.setReason(dto.getReason());
            blacklistEntity.setOrderId(dto.getOrderId());
            blacklistWriteService.insertIgnoreNull(blacklistEntity);


            FamilyMemberEntity memberEntity = new FamilyMemberEntity();
            TmpFamilyMemberEntity tmpMemberEntity = new TmpFamilyMemberEntity();
            memberEntity.setIdcard(familyMember.getIdcard());
            memberEntity.setIsSaveObject(Constant.IsSaveObject.NO);
            BeanUtils.copyProperties(memberEntity,tmpMemberEntity);
            familyMemberWriteService.updateByIdCard(memberEntity);
            tmpFamilyMemberWriteService.updateByIdCard(tmpMemberEntity);
        }

    }


    private void preCheck4AddRecord(AddBlacklistRecordDTO dto) {
        String bizState;
        if (Constant.BusinessCode.LINSHI.equals(dto.getBusinessType())) {
            bizState = tmpOrderReadService.getBizStateById(dto.getOrderId());
        } else {
            bizState = orderReadService.getBizStateById(dto.getOrderId());
        }


        if (StringUtils.isEmpty(bizState)) {
            throw new BizException(FailureCode.ERR_10003);
        }


        if (!Constant.BizStateNew.APPROVE_REFUSE.equals(bizState) || !Constant.BizStateTmp.APPROVE_REFUSE.equals(bizState)) {
            throw new BizException(FailureCode.ERR_20063);
        }

        List<String> idcards = dto.getIdcards();

        for (String idcard : idcards) {

            List<OrderEntity> list;

            list = orderReadService.listAnyTodoByIdCard(idcard);
            if (list.size() > 0) {
                for (OrderEntity orderEntity : list) {
                    TaDictPo bizTypeDict = dictionaryReadService.getCodeCache(DictConstant.BUSINESS_TYPE, orderEntity.getBusinessType());
                    TaDictPo operTypeDict = dictionaryReadService.getCodeCache(DictConstant.OPERATION_TYPE, orderEntity.getType());
                    TaDictPo stateDict = dictionaryReadService.getCodeCache(DictConstant.BUSINESS_STATUS, orderEntity.getState());

                    StringBuilder msg = new StringBuilder();
                    msg.append("姓名：").append(orderEntity.getName())
                            .append("身份证号码：").append(orderEntity.getIdcard())
                            .append("，该人员正在办理").append(bizTypeDict.getLabel()).append("(" + operTypeDict.getLabel() + "),")
                            .append("状态：").append(stateDict.getLabel())
                            .append("，不可将其加入黑名单。");

                    throw new BizException("-1",msg.toString());
                }
            }


            list = orderReadService.listAnyNotExpireOrderByIdCard(idcard);

            if (list.size() > 0) {
                for (OrderEntity orderEntity : list) {
                    TaDictPo bizTypeDict = dictionaryReadService.getCodeCache(DictConstant.BUSINESS_TYPE, orderEntity.getType());

                    StringBuilder msg = new StringBuilder();
                    msg.append("姓名：").append(orderEntity.getName())
                            .append("身份证号码：").append(orderEntity.getIdcard())
                            .append("，该人员正在享受").append(bizTypeDict.getLabel())
                            .append("，不可将其加入黑名单。");

                    throw new BizException(msg.toString());
                }
            }


            BlacklistEntity blacklistEntity = blacklistReadService.getByIdCard(idcard);
            if (blacklistEntity != null) {
                throw new BizException("-1","姓名：" + blacklistEntity.getName() + "，身份证号码：" + blacklistEntity.getIdcard() + "，该人员正在黑名单中。");
            }
        }
    }
}
